import requests
import time
import execjs
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import binascii


def get_vid(url):
    vid = url.split('&')[1].split('=')[1]
    return vid


def get_ctime():
    now = time.time()
    t = time.localtime(now)
    t = time.strftime('%Y-%m-%d %H:%M:%S')
    return t


def get_pid():
    node = execjs.get()
    fp = open('./pid.js', 'r', encoding='utf-8')
    ctx = node.compile(fp.read())
    pid = ctx.eval('createGUID()')
    return pid


def get_Gn(vid):
    s = "|%s|%s|mg3c3b04ba|1.25.0|lgrw9mi0_ohe75k0may|4330701|https://w.yangshipin.cn/|mozilla/5.0 (windows nt ||Mozilla|Netscape|Win32|"
    ctime = str(int(time.time()))
    Gn = s % (vid, ctime)
    return Gn


def get_qn(Vn):
    node = execjs.get()
    fp = open('./qn.js', 'r', encoding='utf-8')
    ctx = node.compile(fp.read())
    qn = ctx.eval("get_qn('%s')" % Vn)
    return str(qn)


def aes_encrypt(data_string):
    key_string = "4E2918885FD98109869D14E0231A0BF4"
    key = binascii.a2b_hex(key_string)

    iv_string = "16B17E519DDD0CE5B79D7A63A4DD801C"
    iv = binascii.a2b_hex(iv_string)

    aes = AES.new(
        key=key,
        mode=AES.MODE_CBC,
        iv=iv
    )
    raw = pad(data_string.encode('utf-8'), 16)
    aes_bytes = aes.encrypt(raw)
    return binascii.b2a_hex(aes_bytes).decode().upper()


def get_ckey(qn, Gn):
    data = '|' + qn + Gn
    result = aes_encrypt(data)
    ckey = '--01' + result
    return ckey


def get_vkey(vid, ckey, pid):
    url = "https://playvv.yangshipin.cn/playvinfo"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
        "referer": "https://w.yangshipin.cn/",
        'cookie': "guid=lgrw9mi0_ohe75k0may"
    }
    params = {
        "callback": "jsonp1",
        "guid": "lgrw9mi0_ohe75k0may",
        "platform": "4330701",
        "vid": vid,
        "defn": "auto",
        "charge": "0",
        "defaultfmt": "auto",
        "otype": "json",
        "defnpayver": "1",
        "appVer": "1.25.0",
        "sphttps": "1",
        "sphls": "1",
        "spwm": "4",
        "dtype": "3",
        "defsrc": "1",
        "encryptVer": "8.1",
        "sdtfrom": "4330701",
        "cKey": ckey,
        "panoramic": "false",
        "flowid": pid,
    }

    ret = requests.get(url=url, headers=headers, params=params).text

    def jsonp1(arg):
        return arg

    ret = eval(ret)
    fn = ret['vl']['vi'][0]['fn']
    fvkey = ret['vl']['vi'][0]['fvkey']
    return fn, fvkey


def get_vurl(fn, fvkey):
    return "https://mp4playali-cdn.ysp.cctv.cn/%s?sdtfrom=4330701&guid=lgrw9mi0_ohe75k0may&vkey=%s&platform=2" % (
        fn, fvkey)


def up(ctime, vid, pid, vurl):
    url = ""
    data = {
        "ctime": ctime,
        "ua": "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/112.0.0.0 safari/537.36",
        "hh_ua": "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/112.0.0.0 safari/537.36",
        "platform": "4330701",
        "guid": "lgrw9mi0_ohe75k0may",
        "Pwd": "1698957057",
        "version": "wc - 1.25.0",
        "url": "https: // w.yangshipin.cn / video?type = 0 & vid = %s" % vid,
        "hh_ref": "https: // w.yangshipin.cn / video?type = 0 & vid = %s" % vid,
        "vid": vid,
        "isfocustab": "1",
        "isvisible": "1",
        "idx": "0",
        "val": "657",
        "pid": pid,
        "bi": "0",
        "bt": "0",
        "defn": "hd",
        "vurl": vurl,
        "step": 6,
        "val1": 1,
        "val2": 1,
    }


def down_video(down_url, fn):
    ret = requests.get(url=down_url).content
    with open(fn, mode='wb') as f:
        f.write(ret)


video_url = "https://w.yangshipin.cn/video?type=0&vid=y000023mueq"
vid = get_vid(video_url)
ctime = get_ctime()
pid = get_pid()
Gn = get_Gn(vid=vid)
qn = get_qn(Vn=Gn)
ckey = get_ckey(qn, Gn)
fn, fvkey = get_vkey(vid, ckey, pid)
vurl = get_vurl(fn, fvkey)
up(ctime, vid, pid, vurl)
print("刷播放量成功!")
down_url = 'https://mp4playali-cdn.ysp.cctv.cn/%s?sdtfrom=4330701&guid=lgrw9mi0_ohe75k0may&vkey=%s&platform=2' % (
    fn, vurl)
down_video(down_url, fn)
print(fn, ":下载成功!")
